package com.csgc.camera.biz

import android.animation.Animator
import android.animation.Animator.AnimatorListener
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.ActivityInfo
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Typeface
import android.hardware.Camera
import android.media.AudioManager
import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import android.os.SystemClock
import android.os.Vibrator
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import cn.bingoogolapple.transformerstip.TransformersTip
import cn.bingoogolapple.transformerstip.gravity.TipGravity
import coil.load
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.amap.apis.utils.core.api.AMapUtilCoreApi
import com.csgc.camera.base.BaseBindingActivity
import com.csgc.camera.biz.other.LoginActivity
import com.csgc.camera.biz.other.activity.AboutActivity
import com.csgc.camera.biz.other.activity.CameraSettingActivity
import com.csgc.camera.biz.other.activity.EditImageActivity
import com.csgc.camera.biz.other.activity.FeedBackActivity
import com.csgc.camera.biz.other.activity.LocationSelectActivity
import com.csgc.camera.biz.other.activity.PuzzleActivity
import com.csgc.camera.biz.other.activity.WebViewActivity
import com.csgc.camera.biz.vip.VipCenterActivity
import com.csgc.camera.broad.TimeChangeReceiver
import com.csgc.camera.constants.Constants
import com.csgc.camera.constants.MaskConfig
import com.csgc.camera.events.ApplyMaskEvent
import com.csgc.camera.events.AutoSaveImageEvents
import com.csgc.camera.events.BuyVipEvents
import com.csgc.camera.events.ChangeCustomMaskStatusEvent
import com.csgc.camera.events.ChangeMaskEvent
import com.csgc.camera.events.CustomMaskEvent
import com.csgc.camera.events.DeleteAlbumEvents
import com.csgc.camera.events.JumpToLocationEvent
import com.csgc.camera.events.LoginEvents
import com.csgc.camera.events.LogoutEvents
import com.csgc.camera.events.MaskLocationEvent
import com.csgc.camera.events.PuzzleSaveEvents
import com.csgc.camera.events.ReferenceLineEvents
import com.csgc.camera.events.RewardTempVipEvents
import com.csgc.camera.events.TakeSoundEvents
import com.csgc.camera.events.TempVipExpireEvents
import com.csgc.camera.events.VibratingEvents
import com.csgc.camera.events.showMaskEditDialogEvent
import com.csgc.camera.http.viewmodel.AppViewModel
import com.csgc.camera.storage.MaskPreference
import com.csgc.camera.storage.PermissionRequestPreference
import com.csgc.camera.storage.SettingPreference
import com.csgc.camera.storage.UserPreference
import com.csgc.camera.util.CommonUtils
import com.csgc.camera.util.ImageUtil
import com.csgc.camera.util.SpUtils
import com.csgc.camera.util.ViewUnit
import com.csgc.camera.util.ViewUtils
import com.csgc.camera.util.clickWithTrigger
import com.csgc.camera.util.dp
import com.csgc.camera.util.saveToAlbum
import com.csgc.camera.util.startTime
import com.csgc.camera.widget.CoilEngine
import com.csgc.camera.widget.DefNotification
import com.csgc.camera.widget.IPuzzleUpdate
import com.csgc.camera.widget.dialog.CommonHandleTipsDialog
import com.csgc.camera.widget.dialog.ContactUsDialog
import com.csgc.camera.widget.dialog.CustomMaskHandle
import com.csgc.camera.widget.dialog.FilterChooseDialog
import com.csgc.camera.widget.dialog.FunctionGuideDialog
import com.csgc.camera.widget.dialog.LoadingPop
import com.csgc.camera.widget.dialog.MaskChooseDialog
import com.csgc.camera.widget.dialog.MaskEditDialog
import com.csgc.camera.widget.dialog.PuzzleStyleDialog
import com.csgc.camera.widget.dialog.UserAgreementDialog
import com.csgc.camera.widget.puzzle.PuzzleStyle1
import com.csgc.camera.widget.puzzle.PuzzleStyle2
import com.csgc.camera.widget.puzzle.PuzzleStyle3
import com.csgc.camera.widget.puzzle.PuzzleStyle4
import com.cysd.spsyxj.R
import com.cysd.spsyxj.databinding.ActivityMainBinding
import com.drake.channel.receiveEvent
import com.drake.channel.sendEvent
import com.elvishew.xlog.XLog
import com.gyf.immersionbar.ktx.immersionBar
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.hjq.shape.view.ShapeTextView
import com.hjq.toast.ToastUtils
import com.hlyj.http.base.tool.lib_hlyj_base.bean.BaseResult
import com.hlyj.http.base.tool.lib_hlyj_base.camera.UserInfoResultBean
import com.hlyj.http.base.tool.lib_hlyj_base.net.ApiCallback
import com.hlyj.http.base.tool.lib_hlyj_base.utils.BaseAppConstans
import com.hlyj.http.base.tool.lib_hlyj_base.utils.BaseModuleSpUtils
import com.hlyj.http.base.tool.lib_hlyj_base.utils.MMKVUtils
import com.hnyyac.ad.mds.IAdView
import com.hnyyac.ad.mds.IAdViewListener
import com.hnyyac.ad.mds.manager.AdManager
import com.hnyyac.ad.mds.manager.AdManager.AdLoadListener
import com.hnyyac.ad.mds.utils.BaseAdConstants
import com.hnyyac.ad.mds.utils.BaseAdSpUtils
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.language.LanguageConfig
import com.luck.picture.lib.style.PictureSelectorStyle
import com.luck.picture.lib.style.SelectMainStyle
import com.luck.picture.lib.utils.SdkVersionUtils
import com.ok.common.api.GlobalApi
import io.microshow.rxffmpeg.RxFFmpegInvoke
import io.microshow.rxffmpeg.RxFFmpegSubscriber
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.wysaid.common.Common
import org.wysaid.nativePort.CGENativeLibrary
import java.io.File
import java.io.IOException
import java.io.InputStream


class MainActivity : BaseBindingActivity<ActivityMainBinding>(ActivityMainBinding::inflate),IAdViewListener {
    var app_process: String? = "0" //整个应用流程
    var type_proces: String? = null //功能入口类型
//    var logininfo:LoginResultBean?=null
//    var userInfo:UserInfoResultBean?=null
    companion object {
        fun launch(context: Context) {
            context.startActivity(Intent(context, MainActivity::class.java))
        }
    }


    private val viewModel:AppViewModel by viewModels()
    private var flashModel = Camera.Parameters.FLASH_MODE_OFF

    private var logoMaskPath = ""

    private var currentCameraUri: Uri?=null

    //0_9:16 1_3:4 2_1:1
    private var cameraSizeType = 0

    //拍摄倒计时
    private var cameraCountDown = 0
    //0 视频 1拍摄 2拼图
    private var cameraType = 1
    // 3 4 6 9---- 1
    private var puzzleStyle = 1
    //拼图个数
    private val puzzleList:ArrayList<String> by lazy {
        ArrayList()
    }
    //拼图样式
    private var puzzleStyleViewUpdate: IPuzzleUpdate?=null
    //0未开始录制 1开始录制
    private var recordType = 0
    //录制倒计时
    private var recordIngJob: Job?=null
    //录制视频路径
    private var recordPath = ""
    //录制时间
    private var videoRecordingTime = 0L
    //参考线显示状态
    private var referenceLineStatus = false
    //震动状态
    private var takeVibrating = false
    //拍照声音
    private var takeSound = true
    //当前系统音量
    private var currentPhoneVolume = 0
    //是否保存到相册
    private var isNeedSaveAlbum = true
    //是否添加logo水印
    private var isNeedLogoWaterMark = true
    //缩放
    var zoom = 1

    //logoBitmapWatermark
    private val logoWaterMark:Bitmap by lazy {
        BitmapFactory.decodeResource(resources, R.drawable.img_logo_mask)
    }

    //是否视频拍摄处理中
    private var isRecordingHandle = false


    private val loadingPop: LoadingPop by lazy {
        LoadingPop(this,false)
    }


    //拍摄声音
    private val mMediaPlayer:MediaPlayer by lazy {
        MediaPlayer.create(this, R.raw.take_photo_shutter)
    }

    private var currentFilterConfig = ""
    private val filterDialog: FilterChooseDialog by lazy {
       val dialog =  FilterChooseDialog(this)
        dialog.setListener(object :FilterChooseDialog.OnFilterChooseListener{
            override fun onItemCLick(filter: String) {
                currentFilterConfig = filter
                binding.myGLSurfaceView.setFilterWithConfig(filter)
            }
        })
        dialog
    }

    private val mLoadImageCallback: CGENativeLibrary.LoadImageCallback by lazy {
        object :CGENativeLibrary.LoadImageCallback{
            override fun loadImage(name: String?, p1: Any?): Bitmap? {
                val am = assets
                val `is`: InputStream = try {
                    am.open(name!!)
                } catch (e: IOException) {
                    Log.e(Common.LOG_TAG, "Can not open file $name")
                    return null
                }

                return BitmapFactory.decodeStream(`is`)
            }

            override fun loadImageOK(bmp: Bitmap?, p1: Any?) {
                bmp?.recycle()
            }
        }
    }

    /**
     * 水印dialog
     */
    private val maskBottom:MaskChooseDialog by lazy {
        MaskChooseDialog()

    }

    private val timeChangeReceiver: TimeChangeReceiver by lazy {
        TimeChangeReceiver()
    }
    private val timeFilter:IntentFilter by lazy {
        val filter = IntentFilter()

        filter.addAction(Intent.ACTION_TIME_TICK)
        filter.addAction(Intent.ACTION_TIME_CHANGED)
        filter
    }

    // 修改为 lateinit 声明，确保在权限获取后再初始化
    private lateinit var mLocationClient: AMapLocationClient
    private var locationLat:Double = 0.0
    private var locationLng:Double = 0.0
    private var street:String = ""
     //高德地图定位回调
    private val mLocationListener: AMapLocationListener by lazy {
        AMapLocationListener {

            locationLat = it.latitude
            locationLng = it.longitude
            street = it.street


            MaskConfig.setLocationStyle(it.province,it.city,it.district,it.street,it.poiName)
            //MaskConfig.maskLocation = "${it.province}${it.city}${it.district}${it.street}${it.poiName}"

//            sendEvent(MaskLocationEvent(location = "${it.province}${it.city}${it.district}${it.street}${it.poiName}"))
            //发送定位事件
            sendEvent(MaskLocationEvent(location = MaskConfig.maskLocation))

            // 确保已经初始化了才调用
            if (::mLocationClient.isInitialized) {
                mLocationClient.onDestroy()
            }

        }
    }
    private val mLocationOption: AMapLocationClientOption by lazy {
       val option =  AMapLocationClientOption()
        option.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
        option.isOnceLocation = true
        option.isOnceLocationLatest = true
        option.isNeedAddress = true
        option.isLocationCacheEnable = false // 禁用定位缓存
        option.isWifiActiveScan = false // 禁用WIFI主动扫描
        option.isSensorEnable = false // 禁用传感器
        option.httpTimeOut = 10000 // 设置超时时间
        option
    }

    private var permissionTipTitle:String = ""
    private var permissionTipContent:String = ""
    //权限申请拒绝不再显示引导dialog
    private val permissionDialog:CommonHandleTipsDialog by lazy {
        val dialog = CommonHandleTipsDialog(
            this, title = "", leftTxt = "取消", rightTxt = "去开启",
            content = ""
        )
        dialog.listener = object :CommonHandleTipsDialog.DialogActionListener{
            override fun sure(type:String) {
                if(type == Permission.CAMERA){
                    if(!XXPermissions.isGranted(this@MainActivity,Permission.CAMERA) && !XXPermissions.isGranted(this@MainActivity,Permission.WRITE_EXTERNAL_STORAGE)){
                        permissionNotification(permissionTipTitle,permissionTipContent)
                        initPermission(Permission.CAMERA,Permission.WRITE_EXTERNAL_STORAGE)
                    }else if(!XXPermissions.isGranted(this@MainActivity,Permission.CAMERA)){
                        permissionNotification(permissionTipTitle,permissionTipContent)
                        initPermission(Permission.CAMERA)
                    }else if (!XXPermissions.isGranted(this@MainActivity,Permission.WRITE_EXTERNAL_STORAGE)){
                        permissionNotification(permissionTipTitle,permissionTipContent)
                        initPermission(Permission.WRITE_EXTERNAL_STORAGE)
                    }
                }else if (type == Permission.ACCESS_FINE_LOCATION){
                    permissionNotification(permissionTipTitle,permissionTipContent)
                    locationRequest()
                }else if (type == Permission.RECORD_AUDIO){
                    permissionNotification(permissionTipTitle,permissionTipContent)
                    videoPermissionRequest()
                }else if (type == Permission.WRITE_EXTERNAL_STORAGE){
                    permissionNotification(permissionTipTitle,permissionTipContent)
                    albumPermissionRequest()
                }else if (type == Permission.READ_MEDIA_IMAGES){
                    //14 相册权限 读取图片
                    permissionNotification(permissionTipTitle,permissionTipContent)
                    requestAlbumPermission()

                }

            }
        }

        dialog
    }

    private var defNotification: DefNotification? = null

   /* private val defNotification: DefNotification by lazy {
       val notify =  DefNotification(this)
        notify.setContentView(R.layout.notification_permission)
        notify.setDuration(3000)
        val icon: ImageView = defNotification.findViewById(R.id.icon)
        icon.setImageResource(R.drawable.ic_launcher)
        notify
    }*/

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        immersionBar {
            fitsSystemWindows(true)
            statusBarColor(R.color.black)
            statusBarDarkFont(false)
        }

        maskType = MaskPreference.instance.getMaskType()
        maskId = MaskPreference.instance.getMaskId()
        MaskConfig.locationStyle = MaskPreference.instance.getLocationStyle()

        initUser()

        initView()
        initEvents()
        drawEvents()

        initLocation()

        registerReceiver(timeChangeReceiver,timeFilter)

        initData()
    }

    private fun initLocation(){

        if(XXPermissions.isGranted(this,Permission.ACCESS_FINE_LOCATION)){

            AMapLocationClient.updatePrivacyShow(this@MainActivity,true,true)
            AMapLocationClient.updatePrivacyAgree(this@MainActivity,true)
            AMapUtilCoreApi.setCollectInfoEnable(false) // 确保统计信息收集被禁用
            mLocationClient = AMapLocationClient(applicationContext)
            mLocationClient.setLocationOption(mLocationOption)
            mLocationClient.setLocationListener(mLocationListener)
            binding.layoutLocationBottomTips.visibility = View.GONE
           // startLocation()
        }
    }
    private fun startLocation(){
        // 确保已经初始化了才调用
        if (::mLocationClient.isInitialized) {
            mLocationClient.startLocation()
        }
    }

    private fun initPermission(vararg permission:String){
        XXPermissions.with(this)
            .permission(permission)
//            .permission(Permission.CAMERA,Permission.WRITE_EXTERNAL_STORAGE)
            .request(object:OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    defNotification?.hide()
                    if (allGranted){
                        binding.layoutPermissionTips.visibility = View.GONE
                    }
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    defNotification?.hide()
                    permissions.forEach {
                        if (it == Permission.CAMERA){
                            if (doNotAskAgain) {
                                val count = PermissionRequestPreference.instance.getCameraCount()
                                if (count == 0) {
                                    PermissionRequestPreference.instance.setCameraCount(count + 1)
                                    return
                                }
                                XXPermissions.startPermissionActivity(this@MainActivity, Permission.CAMERA)
                                return@forEach
                            }

                        }else if(it == Permission.WRITE_EXTERNAL_STORAGE){
                            if (doNotAskAgain) {
                                val count = PermissionRequestPreference.instance.getStorage()
                                if (count == 0) {
                                    PermissionRequestPreference.instance.setStorage(count + 1)
                                    return
                                }
                                XXPermissions.startPermissionActivity(this@MainActivity, Permission.WRITE_EXTERNAL_STORAGE)
                                return@forEach
                            }
                        }

                    }


                }
            })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if(requestCode == XXPermissions.REQUEST_CODE){
            if(XXPermissions.isGranted(this@MainActivity,Permission.CAMERA) && XXPermissions.isGranted(this@MainActivity,Permission.WRITE_EXTERNAL_STORAGE)){
                binding.layoutPermissionTips.visibility = View.GONE
            }else if (XXPermissions.isGranted(this@MainActivity,Permission.ACCESS_FINE_LOCATION)){
                binding.layoutLocationBottomTips.visibility = View.GONE
                //启动定位
               // startLocation()
            }
        }
    }
    override fun onResume() {
        super.onResume()

        binding.myGLSurfaceView.onResume()
        //设置之前的滤镜
        if(currentFilterConfig.isNotEmpty()){
            lifecycleScope.launch(Dispatchers.IO) {
                delay(500)
                lifecycleScope.launch(Dispatchers.Main) {
                    binding.myGLSurfaceView.setFilterWithConfig(currentFilterConfig)
                }
            }
        }

        // 检查是否已经初始化了LocationClient并且需要重新定位
        if (::mLocationClient.isInitialized && locationLat == 0.0 && street.isEmpty() && XXPermissions.isGranted(this, Permission.ACCESS_FINE_LOCATION)){
            startLocation()
        }

    }

    override fun onPause() {
        super.onPause()
        if (binding.myGLSurfaceView.isRecording){
            binding.myGLSurfaceView.endRecording()
        }
        binding.myGLSurfaceView.release(null)
        binding.myGLSurfaceView.onPause()
    }

    override fun onStop() {
        super.onStop()
        // 添加空安全检查
        if (::mLocationClient.isInitialized) {
            mLocationClient.stopLocation()
        }
    }

    private fun initView() {
        app_process = SpUtils.getInstance().getString(BaseAppConstans.APP_PROCESS)

        defNotification = DefNotification(this)
            .setContentView(R.layout.notification_permission)
            .setDuration(3000)
        val icon:ImageView? = defNotification?.findViewById(R.id.icon)
        icon?.setImageResource(R.mipmap.ic_launcher)

        if(XXPermissions.isGranted(this,Permission.CAMERA) && XXPermissions.isGranted(this,Permission.WRITE_EXTERNAL_STORAGE)){
            binding.layoutPermissionTips.visibility = View.GONE
        }else{
            binding.layoutPermissionTips.visibility = View.VISIBLE
        }

        binding.numberMorphView1.period = 1000.0
        binding.numberMorphView2.period = 1000.0
        binding.myGLSurfaceView.presetCameraForward(true)
        binding.myGLSurfaceView.setZOrderOnTop(false)
        binding.myGLSurfaceView.setZOrderMediaOverlay(true)


        maskType = MaskPreference.instance.getMaskType()
        maskId = MaskPreference.instance.getMaskId()
        if(XXPermissions.isGranted(this,Permission.ACCESS_FINE_LOCATION)){
            MaskConfig.maskLocation = "努力获取位置中..."
        }else{
            MaskConfig.maskLocation = "未有定位权限"
        }
        showMaskView()


        //9:16
        val heightPic9_16 = ViewUtils.getScreenWidth(this) * 16 / 8
        val params = binding.myGLSurfaceView.layoutParams as FrameLayout.LayoutParams
        params.height = heightPic9_16
        params.gravity = Gravity.BOTTOM
        binding.myGLSurfaceView.layoutParams = params

        //这里设置了 binding.myGLSurfaceView到宽高也需要设置
        binding.myGLSurfaceView.presetRecordingSize(ViewUtils.getScreenWidth(this), heightPic9_16)
        //拍照图片尺寸 9:16 3:4 1:1 全屏
        binding.myGLSurfaceView.setPictureSize(ViewUtils.getScreenWidth(this), heightPic9_16, true)
        updateLineStyle(heightPic9_16,Gravity.BOTTOM)
        CGENativeLibrary.setLoadImageCallback(mLoadImageCallback, null)

        binding.tvCameraImage.isSelected = true

        binding.ivVipIndex.setOnClickListener {
            VipCenterActivity.launch(this)
        }

        binding.llVip.clickWithTrigger {
//            if (userInfo==null){
//                VipCenterActivity.launch(this)
//            }else{
            LoginActivity.launch(this)
//            }
        }

    }

    private fun initData(){
    //   userInfo=MMKVUtils.getObject(com.hlyj.http.base.tool.lib_hlyj_base.Constants.UserInfoResultBean,UserInfoResultBean::class.java)
//if (userInfo==null || userInfo?.isVip==0){
            when (app_process) {
                "0" -> ""
                "1" -> app_process_1()
                "2" -> app_process_2()
            }
      //  }

//        val token = UserPreference.instance.getUserToken()
//        if (token.isNotEmpty()){
//            viewModel.getUserInfo(UserInfoParams(token))
//        }

//        viewModel.userInfoResult.observe(this){result->
//            result.doSuccess {baseResponse ->
//                baseResponse.data?.let {info->
//                    UserPreference.instance.setUserInfo(userAdapter.toJson(info))
//                    initUser()
//                }
//
//            }
//            result.doFailure {
//            }
//
//        }
    }

    private fun initEvents() {

        receiveEvent<ChangeMaskEvent> {
           showDoubleChaPin()
            maskType = it.type
            maskId = it.id
            showMaskView()
        }


        receiveEvent<ApplyMaskEvent> {
            val isApply = it.isApply
            isNeedLogoWaterMark = isApply
            SettingPreference.instance.setLogoWaterMark(isApply)
        }

        receiveEvent<CustomMaskEvent> {
            currentMask?.onAddCustom()
        }

        receiveEvent<ChangeCustomMaskStatusEvent> {
            currentMask?.changeCustomStatus()
        }

        receiveEvent<showMaskEditDialogEvent> {
            if (maskBottom.isAdded) {
                maskBottom.dismiss()
            }
            editMaskDialog.initData(maskType,maskId)
            editMaskDialog.show(maskType,maskId)
        }

        receiveEvent <DeleteAlbumEvents>{
            currentCameraUri = null
            binding.ivAlbum.load(R.drawable.ic_photo_album)
        }

        //选择地点
        receiveEvent<JumpToLocationEvent> {
            //判断权限
            if(XXPermissions.isGranted(this@MainActivity,Permission.ACCESS_FINE_LOCATION)){
                LocationSelectActivity.launch(this@MainActivity,locationLat,locationLng,street)
            }else{
                permissionTipTitle = "定位权限"
                permissionTipContent = "app需要定位权限才能获取到位置,请授权开启定位权限"
                permissionDialog.showDialog("定位权限","本软件需要定位权限才能获取到位置,请授权开启定位权限",Permission.ACCESS_FINE_LOCATION)
            }

        }


        //拼图保存
        receiveEvent<PuzzleSaveEvents> {
            puzzleList.clear()
            changePuzzle()
        }

        //参考线
        receiveEvent<ReferenceLineEvents> {
            referenceLineStatus = it.show
            if(it.show){
                binding.includeLine.root.visibility = View.VISIBLE
            }else{
                binding.includeLine.root.visibility = View.GONE
            }

        }
        //震动
        receiveEvent<VibratingEvents>{
            takeVibrating = it.status
        }
        //拍摄声音
        receiveEvent<TakeSoundEvents> {
            takeSound = it.status
        }

        //自动保存图片
        receiveEvent<AutoSaveImageEvents> {
            isNeedSaveAlbum = it.status
        }

        //登录
        receiveEvent<LoginEvents> {
            initUser()
        }
        //退出登录
        receiveEvent<LogoutEvents> {
            binding.sbLogoWaterMark.isChecked = true
            initUser()
        }

        //购买VIP
        receiveEvent<BuyVipEvents> {
            initUser()
        }

        //获取到临时会员
        receiveEvent<RewardTempVipEvents> {
            initUser()
            startTempVipTimeTask()
            filterDialog.refreshFilterView()
            editMaskDialog.refreshFilterView()
        }
        //临时会员到期
        receiveEvent<TempVipExpireEvents> {
            initUser()
            filterDialog.refreshFilterView()
            editMaskDialog.refreshFilterView()
            if (!UserPreference.instance.isVip()){
                binding.sbLogoWaterMark.isChecked = true
            }
        }


        referenceLineStatus = SettingPreference.instance.isReferenceLine()
        if(referenceLineStatus){
            binding.includeLine.root.visibility = View.VISIBLE
        }
        takeVibrating = SettingPreference.instance.isCameraVibrating()
        takeSound = SettingPreference.instance.isTakeCameraSound()
        isNeedSaveAlbum = SettingPreference.instance.isAutoSaveImage()

        isNeedLogoWaterMark = SettingPreference.instance.isLogoWaterMark()
        binding.sbLogoWaterMark.isChecked = isNeedLogoWaterMark

        //滤镜
        binding.llCameraFilter.clickWithTrigger {
            filterDialog.show()
        }

        binding.tvProtractor.clickWithTrigger {
            binding.ivProtractor.visibility = if (binding.ivProtractor.visibility == View.VISIBLE) View.GONE else View.VISIBLE
        }

        //拍摄尺寸
        binding.ivCameraSize.clickWithTrigger {
            object : TransformersTip(binding.ivCameraSize, R.layout.pop_size_filter) {
                override fun initView(contentView: View?) {
                    super.initView(contentView)
                    val iv9_16 = contentView?.findViewById<ImageView>(R.id.iv_9_16)
                    val iv3_4 = contentView?.findViewById<ImageView>(R.id.iv_3_4)
                    val iv1_1 = contentView?.findViewById<ImageView>(R.id.iv_1_1)
                    if (cameraSizeType == 0) {
                        iv9_16?.setImageResource(R.drawable.icon_size_16_9_active)
                    } else if (cameraSizeType == 1) {
                        iv3_4?.setImageResource(R.drawable.icon_size_3_4_active)
                    } else if (cameraSizeType == 2) {
                        iv1_1?.setImageResource(R.drawable.icon_size_1_1_active)
                    }

                    iv9_16?.clickWithTrigger {
                        dismissTip()
                        changeSize(0)
                        showDoubleChaPin()
                    }

                    iv3_4?.clickWithTrigger {
                        dismissTip()
                        changeSize(1)
                        showDoubleChaPin()
                    }
                    iv1_1?.clickWithTrigger {
                        dismissTip()
                        changeSize(2)
                        showDoubleChaPin()
                    }


                }
            }.setTipGravity(TipGravity.TO_BOTTOM_CENTER) // 设置浮窗相对于锚点控件展示的位置
                .setTipOffsetXDp(0) // 设置浮窗在 x 轴的偏移量
                .setTipOffsetYDp(10) // 设置浮窗在 y 轴的偏移量

                .setBackgroundDimEnabled(false) // 设置是否允许浮窗的背景变暗
                .setDismissOnTouchOutside(true) // 设置点击浮窗外部时是否自动关闭浮窗

                .show();
        }

        //倒计时
        binding.ivTimeCountDown.clickWithTrigger {
            object : TransformersTip(binding.ivTimeCountDown, R.layout.pop_count_down_filter) {
                override fun initView(contentView: View?) {
                    super.initView(contentView)

                    val countNow = contentView?.findViewById<ImageView>(R.id.iv_count_now)
                    val count3 = contentView?.findViewById<ImageView>(R.id.iv_count_3)
                    val count5 = contentView?.findViewById<ImageView>(R.id.iv_count_5)
                    val count10 = contentView?.findViewById<ImageView>(R.id.iv_count_10)

                    if (cameraCountDown == 0) {
                        countNow?.setImageResource(R.drawable.ic_time_count_now_active)
                    } else if (cameraCountDown == 3) {
                        count3?.setImageResource(R.drawable.ic_time_count_3_active)
                    } else if (cameraCountDown == 5) {
                        count5?.setImageResource(R.drawable.ic_time_count_5_active)
                    } else if (cameraCountDown == 10) {
                        count10?.setImageResource(R.drawable.ic_time_count_10_active)
                    }

                    countNow?.clickWithTrigger {
                        dismissTip()
                        changeCountDown(0)
                        showDoubleChaPin()

                    }

                    count3?.clickWithTrigger {
                        dismissTip()
                        changeCountDown(3)
                        showDoubleChaPin()
                    }
                    count5?.clickWithTrigger {
                        dismissTip()
                        changeCountDown(5)
                        showDoubleChaPin()
                    }
                    count10?.clickWithTrigger {
                        dismissTip()
                        changeCountDown(10)
                        showDoubleChaPin()
                    }


                }
            }.setTipGravity(TipGravity.TO_BOTTOM_CENTER) // 设置浮窗相对于锚点控件展示的位置
                .setTipOffsetXDp(0) // 设置浮窗在 x 轴的偏移量
                .setTipOffsetYDp(14) // 设置浮窗在 y 轴的偏移量

                .setBackgroundDimEnabled(false) // 设置是否允许浮窗的背景变暗
                .setDismissOnTouchOutside(true) // 设置点击浮窗外部时是否自动关闭浮窗

                .show();


        }


        //聚焦
        binding.myGLSurfaceView.setOnTouchListener { v, event ->
            if (event.actionMasked == MotionEvent.ACTION_DOWN) {
                val focusX: Float = event.x / binding.myGLSurfaceView.width
                val focusY: Float = event.y / binding.myGLSurfaceView.height
                binding.myGLSurfaceView.focusAtPoint(focusX, focusY, object : Camera.AutoFocusCallback {
                    override fun onAutoFocus(success: Boolean, camera: Camera?) {
                        if (!success) {
                            binding.myGLSurfaceView.cameraInstance().setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)
                        }
                    }
                })
            }

            true
        }

        //切换前后摄像头
        binding.llSwitchCamera.clickWithTrigger {
            binding.myGLSurfaceView.switchCamera()
            showDoubleChaPin()
        }

        //闪光灯
        binding.ivCameraFish.clickWithTrigger {
            //先检查相机权限
            if (!XXPermissions.isGranted(this@MainActivity,Permission.CAMERA)) {
                ToastUtils.show("请同意相机权限");
                return@clickWithTrigger
            }
            if (flashModel == Camera.Parameters.FLASH_MODE_OFF) {
                flashModel = Camera.Parameters.FLASH_MODE_ON
                binding.ivCameraFish.setImageResource(R.drawable.ic_fish_open_active)
            } else {
                flashModel = Camera.Parameters.FLASH_MODE_OFF
                binding.ivCameraFish.setImageResource(R.drawable.ic_fish_open_close)
            }
            binding.myGLSurfaceView.setFlashLightMode(flashModel)

            showDoubleChaPin()
        }

        //拍照
        binding.ivTakePicture.clickWithTrigger {

            if(XXPermissions.isGranted(this@MainActivity,Permission.CAMERA) && XXPermissions.isGranted(this@MainActivity,Permission.WRITE_EXTERNAL_STORAGE)){
                binding.viewLayerMask.isClickable = true
                if (cameraCountDown == 0) {
                    playTakeSound()
                    takeShotPhoto()
                } else {
                    delayTakeShot()
                }
            }else{
                cameraPermissionRequest()
            }




        }

        //拼图拍照
        binding.tvTakePuzzle.clickWithTrigger {
            if(XXPermissions.isGranted(this@MainActivity,Permission.CAMERA) && XXPermissions.isGranted(this@MainActivity,Permission.WRITE_EXTERNAL_STORAGE)){
                playTakeSound()
                takeShotPhoto()
            }else{
                showSingleInterstitial(3)

            }


        }

        //拍视频
        binding.ivTakeVideo.clickWithTrigger {

            if (isRecordingHandle){
                return@clickWithTrigger
            }

            if(XXPermissions.isGranted(this@MainActivity,Permission.CAMERA) &&
                XXPermissions.isGranted(this@MainActivity,Permission.WRITE_EXTERNAL_STORAGE) &&
                XXPermissions.isGranted(this@MainActivity,Permission.RECORD_AUDIO)){

//                if (!UserPreference.instance.isVip() ){
//                    ToastUtils.show("购买会员开启视频打卡")
//                    VipCenterActivity.launch(this)
//                    return@clickWithTrigger
//                }

                if(!binding.myGLSurfaceView.isRecording){

//                recordPath = externalCacheDir.toString() + "/rec_" + System.currentTimeMillis() + ".mp4"
                    recordPath = getExternalFilesDir(Constants.MASK_RECORD_VIDEO).toString() + "/rec_" + System.currentTimeMillis() + ".mp4"

                    val file = File(recordPath)
                    if(file.exists()){
                        file.delete()
                    }

                    binding.myGLSurfaceView.startRecording(recordPath) {
                        videoRecordingTime = 0
                        if(it){
                            recordType = 1
                            recordingUIStatus(true)
                            //开始计时
                            recordIngJob = lifecycleScope.startTime(duration = 1000, onNext = {
                                videoRecordingTime +=1000
                                binding.tvRecordingTime.text = CommonUtils.stringForTime(videoRecordingTime)
                            })
                        }else{
                            recordIngJob?.cancel()
                            recordType = 0
                            recordingUIStatus(false)
                            binding.ivTakeVideo.setImageResource(R.drawable.ic_index_camera_video_default)
                            ToastUtils.show("录制失败")
                            XLog.e("======record录制失败")
                        }
                    }


                }else{
                    isRecordingHandle = true
                    binding.myGLSurfaceView.endRecording {
                        recordIngJob?.cancel()
                        recordType = 0
                        recordingUIStatus(false)

                        //1.loading
                        lifecycleScope.launch(Dispatchers.Main) {
                            binding.ivTakeVideo.setImageResource(R.drawable.ic_index_camera_video_default)
                            //ToastUtils.show("录制完毕")
                            XLog.e("======record录制完毕")
                            loadingPop.showLoading(true)
                            showDoubleChaPin()
                        }

                        //2.生成水印
                        val maskBitmap = ViewUnit.captureView(binding.layoutMaskContainer)
                        //3.存储水印
                        maskBitmap?.let {
                            val maskName = "todayVideoMask.png"
                            getExternalFilesDir(Constants.MASK_CACHE_IMAGE)?.let { it1 -> CommonUtils.saveBitmapToCache(maskBitmap, it1, maskName) }
                        }
                        val maskPath = "${getExternalFilesDir(Constants.MASK_CACHE_IMAGE)}/todayVideoMask.png"
                        //带水印视频路径
                        val outPath = externalCacheDir.toString() + "/${System.currentTimeMillis()}_rec_mask_video.mp4"

                        //logo水印
                        if (logoMaskPath.isEmpty()){
                            //val tempLogo = BitmapFactory.decodeResource(resources, R.drawable.img_logo_mask)
                            getExternalFilesDir(Constants.MASK_CACHE_IMAGE)?.let { it1 -> CommonUtils.saveBitmapToCache(logoWaterMark, it1, "logoMask.png") }

                            logoMaskPath = "${getExternalFilesDir(Constants.MASK_CACHE_IMAGE)}/logoMask.png"
                        }


                        //4.视频添加水印
                        val commands = if (isNeedLogoWaterMark){
                            val commands = arrayOfNulls<String>(12)
                            commands[0] = "ffmpeg"
                            commands[1] = "-i"
                            commands[2] = recordPath //原视频地址

                            commands[3] = "-i"
                            commands[4] = maskPath //图片水印1地址

                            commands[5] = "-i"
                            commands[6] = logoMaskPath //图片水印2地址
                            commands[7] = "-filter_complex"
                            commands[8] = "[0:v][1:v]overlay=10:main_h-overlay_h-10[bkg1];[bkg1][2:v]overlay=main_w-overlay_w-10:main_h-overlay_h-10"
                            commands[9] = "-codec:a" //音频选项,后加copy表示音频拷贝

                            commands[10] = "copy" //表示音频拷贝,无需处理音频时添加，可节省加水印时间

                            commands[11] = outPath //水印添加完成后的视频文件地址
                            commands
                        }else{
                            val text ="ffmpeg -y -i $recordPath -i $maskPath -filter_complex [0:v]scale=iw:ih[outv0];[1:0]scale=0.0:0.0[outv1];[outv0][outv1]overlay=10:main_h-overlay_h-10 -preset superfast $outPath"
                            text.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                        }
                        //开始执行FFmpeg命令
                        RxFFmpegInvoke.getInstance()
                            .runCommandRxJava(commands)
                            .subscribe(object : RxFFmpegSubscriber() {
                                override fun onError(message: String?) {
                                    loadingPop.dismissLoading()
                                }

                                override fun onFinish() {
                                    //5.复制视频到相册或者pictures

                                    CommonUtils.saveVideoToDCIM(this@MainActivity,outPath,"${System.currentTimeMillis()}_mask_video", onFinish = {
                                        File(outPath).delete()
                                    }, onFail = {})


                                    loadingPop.dismissLoading()
                                    ToastUtils.show("已保存到相册")
                                    isRecordingHandle = false
                                }

                                override fun onProgress(progress: Int, progressTime: Long) {
                                   var tempProgress = progress
                                    if (tempProgress>=95){
                                        tempProgress = 95
                                    }
                                    loadingPop.updateProgress(tempProgress)
                                }

                                override fun onCancel() {
                                    loadingPop.dismissLoading()
                                }
                            })




                    }
                }


            }else{


                var title = "权限申请"
                var content = ""
                if(!XXPermissions.isGranted(this,Permission.CAMERA) && !XXPermissions.isGranted(this,Permission.WRITE_EXTERNAL_STORAGE) && !XXPermissions.isGranted(this,Permission.RECORD_AUDIO)){
                    content = "本软件需要相机权限,录音权限和存储权限才能正常拍摄存储视频,请开启授予相关权限"
                }else if(!XXPermissions.isGranted(this,Permission.CAMERA)){

                    title = "相机权限申请"
                    content = "本软件需要相机权限才能正常拍摄视频,请开启授予相关权限"
                }else if (!XXPermissions.isGranted(this,Permission.WRITE_EXTERNAL_STORAGE)){
                    title = "存储权限申请"
                    content = "本软件需要存储权限才能正常存储视频,请开启授予相关权限"
                }else if (!XXPermissions.isGranted(this,Permission.RECORD_AUDIO)){
                    title = "录音权限申请"
                    content = "本软件需要录音权限才能正常拍摄者视频,请开启授予相关权限"
                }
                permissionTipTitle = title
                permissionTipContent = content
                permissionDialog.showDialog(title,content,Permission.RECORD_AUDIO)

            }
        }

        //打开侧边栏
        binding.ivDrawerMenu.clickWithTrigger {
            showDoubleChaPin()
             binding.layoutDrawer.open()
           // UserCenterActivity.launch(this)
        }

        //位置设置
        binding.tvLocation.clickWithTrigger {
            if(XXPermissions.isGranted(this,Permission.ACCESS_FINE_LOCATION)){
                LocationSelectActivity.launch(this,locationLat,locationLng,street)
            }else{
                //dialog 提示需要定位权限
                permissionTipTitle = "定位权限"
                permissionTipContent = "本软件需要要定位权限才能获取到位置,请授权开启定位权限"
                permissionDialog.showDialog("定位权限","本软件需要定位权限才能获取到位置,请授权开启定位权限",Permission.ACCESS_FINE_LOCATION)
            }

        }

        //打开相册
        binding.layoutAlbum.clickWithTrigger {

            if (!XXPermissions.isGranted(this,Permission.WRITE_EXTERNAL_STORAGE)){
                permissionTipTitle = "存储权限"
                permissionTipContent = "本软件需要存储权限才能显示手机中的图片,请授权开启存储权限"
                permissionDialog.showDialog("存储权限","本软件需要存储权限才能显示手机中的图片,请授权开启存储权限",Permission.WRITE_EXTERNAL_STORAGE)
                return@clickWithTrigger
            }

            if (SdkVersionUtils.isTIRAMISU()){
                if (!XXPermissions.isGranted(this,Permission.READ_MEDIA_IMAGES)){
                    permissionTipTitle = "相册权限"
                    permissionTipContent = "本软件需要相册权限才能显示手机中的图片,请授权相册权限"
                    permissionDialog.showDialog("相册权限","本软件需要相册权限才能显示手机中的图片,请授权相册权限",Permission.READ_MEDIA_IMAGES)
                    return@clickWithTrigger
                }
            }

            if (currentCameraUri!=null){

                EditImageActivity.launch(this,currentCameraUri.toString())

            }else{
                val picStyle = PictureSelectorStyle()
                val selectStyle = SelectMainStyle()
                selectStyle.selectText = "确定"

                picStyle.selectMainStyle = selectStyle
                PictureSelector.create(this)
                    .openGallery(SelectMimeType.ofImage())
                    .setImageEngine(CoilEngine())
                    .setLanguage(LanguageConfig.CHINESE)
                    .setSelectionMode(SelectModeConfig.SINGLE)
                    .setImageSpanCount(3)
                    .isGif(false)
                    .isBmp(false)
                    .isWebp(false)
                    .setSkipCropMimeType()
                    .isDisplayCamera(false)
                    .isPreviewImage(false)
                    .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                    .setSelectorUIStyle(picStyle)
                    .forResult(object : OnResultCallbackListener<LocalMedia?> {
                        override fun onResult(result: ArrayList<LocalMedia?>) {
                            result[0]?.let {

                                if (it.path.startsWith("content://")){
                                    EditImageActivity.launch(this@MainActivity,it.path)
                                }else{
                                    EditImageActivity.launchPath(this@MainActivity,it.path)
                                }

                            }

                        }
                        override fun onCancel() {}
                    })
            }



        }

        //申请相机权限
        binding.layoutPermissionTips.clickWithTrigger {
            cameraPermissionRequest()
        }


        binding.tvCameraVideo.clickWithTrigger {
            animationTab(0)
            //视频
        }
        binding.tvCameraImage.clickWithTrigger {
            animationTab(1)
        }

        binding.tvCameraPuzzle.clickWithTrigger {
            animationTab(2)
        }

        binding.tvMask.clickWithTrigger {
            showSingleInterstitial(4)
            maskBottom.showDialog(supportFragmentManager,"mask")
        }

        binding.ivCloseLocationBottomTips.clickWithTrigger {
            binding.layoutLocationBottomTips.visibility = View.GONE
        }
        binding.stvRequestLocation.clickWithTrigger {
            permissionTipTitle = "定位权限"
            permissionTipContent = "本软件需要定位权限才能获取到位置,请授权开启定位权限"
            permissionDialog.showDialog("定位权限","本软件需要定位权限才能获取到位置,请授权开启定位权限",Permission.ACCESS_FINE_LOCATION)
        }

        binding.layoutMaskContainer.clickWithTrigger {
            showSingleInterstitial(5)
            editMaskDialog.initData(maskType,maskId)
            editMaskDialog.show(maskType,maskId)
        }

        //退出连拍
//        binding.tvQuitePuzzle.clickWithTrigger {
//            puzzleList.forEach {
//                File(it).delete()
//            }
//            puzzleList.clear()
//            changePuzzle()
//        }
        //撤销
        binding.tvPuzzleRepeal.clickWithTrigger {
           val path =  puzzleList.removeAt(puzzleList.size-1)
            File(path).delete()
            changePuzzle()
        }
        //保存
        binding.tvPuzzleSave.clickWithTrigger {
            var ratioWidth = 9
            var ratioHeight = 16
            if(cameraSizeType == 1){
                 ratioWidth = 3
                 ratioHeight = 4
            }else if(cameraSizeType == 2){
                 ratioWidth = 1
                 ratioHeight = 1
            }

            PuzzleActivity.launch(this,puzzleList,puzzleStyle,ratioWidth,ratioHeight)
        }

        //选择拼图样式
        binding.tvChangePuzzle.clickWithTrigger {
            puzzleStyleDialog.show()
        }
    }



    private fun locationRequest(){
        if(!XXPermissions.isGranted(this,Permission.ACCESS_FINE_LOCATION)){
            XXPermissions.with(this)
                .permission(Permission.ACCESS_FINE_LOCATION)
                .request(object:OnPermissionCallback{
                    override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                        defNotification?.hide()
                        if(allGranted){
                            //binding.layoutLocationBottomTips.visibility = View.GONE
                            initLocation()
                            startLocation()
                        }
                    }

                    override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                        defNotification?.hide()
                        if (doNotAskAgain) {
                            val count = PermissionRequestPreference.instance.getLocationCount()
                            if (count == 0) {
                                PermissionRequestPreference.instance.setLocationCount(count + 1)
                                return
                            }
                            XXPermissions.startPermissionActivity(this@MainActivity, Permission.ACCESS_FINE_LOCATION)

                        }
                    }
                })
        }
    }

    private fun takeShotPhoto() {
//        if (userInfo?.isVip==0 && SettingPreference.instance.getTakePhotoCount() >= 3){
//            ToastUtils.show("购买会员畅享无限拍摄")
//            VipCenterActivity.launch(this)
//            return
//        }

        //拼图超过张数不继续拍照
        if(cameraType == 2){
            if (puzzleStyle == 1 && puzzleList.size == 3){
                changePuzzle()
                return
            }else if(puzzleStyle == 2 && puzzleList.size == 4){
                changePuzzle()
                return
            }else if(puzzleStyle == 3 && puzzleList.size == 6){
                changePuzzle()
                return
            }else if(puzzleStyle == 4 && puzzleList.size == 9){
                changePuzzle()
                return
            }
        }

        binding.myGLSurfaceView.setFlashLightMode(flashModel)
        takeVibrator()
        binding.myGLSurfaceView.takePicture({bitmap->
            if (bitmap == null){
                return@takePicture
            }
            SettingPreference.instance.setTakePhoto()

            loadingPop.showLoading()
            //1.生成水印
            val maskBitmap = ViewUnit.captureView(binding.layoutMaskContainer)
            showDoubleChaPin()//插广告
            if(cameraSizeType == 2){
                //1:1拍照样式 处理拍照图片比例
                //拍照图片

                var scaleBitmap:Bitmap
                try {
                    scaleBitmap =  Bitmap.createBitmap(bitmap,0,(bitmap.height-bitmap.width)/2,bitmap.width,bitmap.width)
                }catch (e:Exception){
                    scaleBitmap = bitmap
                }
                //2.带水印照片
                val finalBitmap = if (isNeedLogoWaterMark){
                    ImageUtil.createWaterMaskBottomLeftAndRight(scaleBitmap,maskBitmap,logoWaterMark,-5,15,10)
                }else{
                    ImageUtil.createWaterMaskLeftBottom(scaleBitmap,maskBitmap,-5,15)
                }

                //存储到私有目录---无水印照片--名字要是一样带
                val name = "today_mask_${System.currentTimeMillis()}.png"

                if(cameraType != 2){
                    //拍单张
                    lifecycleScope.launch(Dispatchers.IO) {
                        //无水印存储到私有目录
                        CommonUtils.saveBitmapToCache(scaleBitmap,getExternalFilesDir(Constants.NO_MASK_CACHE_IMAGE)!!,name)
                    }
                    if(isNeedSaveAlbum){

                        lifecycleScope.launch(Dispatchers.IO) {
                            //水印图存储到相册
                            val uri = finalBitmap?.saveToAlbum(this@MainActivity,name,null,100)
                            lifecycleScope.launch(Dispatchers.Main) {
                                binding.ivAlbum.load(uri)
                                currentCameraUri = uri
                                loadingPop.dismissLoading()
                                //showDoubleChaPin()
                            }
                        }

                    }else{
                        lifecycleScope.launch(Dispatchers.IO) {
                            //无水印存储到私有目录
                            val cachePath =  CommonUtils.saveBitmapToCache(finalBitmap,getExternalFilesDir(Constants.HAVE_MASK_CACHE_IMAGE)!!,name)

                            lifecycleScope.launch(Dispatchers.Main) {
                                loadingPop.dismissLoading()
                                EditImageActivity.launchShare(this@MainActivity,cachePath)
                                //showDoubleChaPin()
                            }
                        }
                    }



                }else{
                    //拼图拍摄
                    val path =  CommonUtils.saveBitmapToCache(finalBitmap,getExternalFilesDir(Constants.PUZZLE_CACHE_IMAGE)!!,"puzzle_${System.currentTimeMillis()}.png")
                    puzzleList.add(path)
                    changePuzzle()
                    loadingPop.dismissLoading()
                }

                binding.viewLayerMask.isClickable = false
            }else{
                //2.带水印照片
              val finalBitmap = if (isNeedLogoWaterMark){
                  ImageUtil.createWaterMaskBottomLeftAndRight(bitmap,maskBitmap,logoWaterMark,-5,15,10)
                }else{
                  ImageUtil.createWaterMaskLeftBottom(bitmap,maskBitmap,-5,15)
                }


                //存储到私有目录---无水印照片--名字要是一样的
                val name = "today_mask_${System.currentTimeMillis()}.png"
                if(cameraType != 2){
                    //拍单张
                    lifecycleScope.launch(Dispatchers.IO) {
                        //无水印存储到私有目录
                        CommonUtils.saveBitmapToCache(bitmap,getExternalFilesDir(Constants.NO_MASK_CACHE_IMAGE)!!,name)
                    }

                    if (isNeedSaveAlbum){

                        lifecycleScope.launch(Dispatchers.IO) {
                            //水印图存储到相册
                            val uri = finalBitmap?.saveToAlbum(this@MainActivity,name,null,100)
                            lifecycleScope.launch(Dispatchers.Main) {
                                binding.ivAlbum.load(uri)
                                currentCameraUri = uri
                                loadingPop.dismissLoading()
                            }
                        }
                    }else{
                        lifecycleScope.launch(Dispatchers.IO) {
                            //无水印存储到私有目录
                           val cachePath =  CommonUtils.saveBitmapToCache(finalBitmap,getExternalFilesDir(Constants.HAVE_MASK_CACHE_IMAGE)!!,name)

                            lifecycleScope.launch(Dispatchers.Main) {
                                loadingPop.dismissLoading()
                                EditImageActivity.launchShare(this@MainActivity,cachePath)
                            }
                        }
                    }


                }else{
                    //拼图拍摄

                   val path =  CommonUtils.saveBitmapToCache(finalBitmap,getExternalFilesDir(Constants.PUZZLE_CACHE_IMAGE)!!,"puzzle_${System.currentTimeMillis()}.png")
                    puzzleList.add(path)
                    changePuzzle()
                    loadingPop.dismissLoading()
                }

                binding.viewLayerMask.isClickable = false



            }

            if(!takeSound){
                lifecycleScope.launch(Dispatchers.IO) {
                    delay(800)
                    audio.setStreamVolume(AudioManager.STREAM_MUSIC,currentPhoneVolume,AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE)
                }

            }
        },{},currentFilterConfig,1.0f, true)





    }

    private fun delayTakeShot() {
        binding.layoutCountNum.visibility = View.VISIBLE
        CommonUtils.countDownCoroutines(cameraCountDown, {
            //显示倒计时
            if(it == 10){
                binding.numberMorphView1.visibility = View.VISIBLE
                binding.numberMorphView1.currentNum = 1
                binding.numberMorphView2.currentNum = 0
            }else{
                binding.numberMorphView1.visibility = View.GONE
                binding.numberMorphView2.currentNum = it
            }

        }, {
            binding.layoutCountNum.visibility = View.GONE
            playTakeSound()
            takeShotPhoto()
        }, lifecycleScope)

    }


    private fun changeSize(type: Int) {
        if (type == cameraSizeType) {
            return
        }

        binding.myGLSurfaceView.release(null)
        binding.myGLSurfaceView.onPause()

        cameraSizeType = type
        if (cameraSizeType == 0) {
          //  binding.ivCameraSize.setImageResource(R.drawable.icon_size_16_9_active)
            val heightPic8_16 = ViewUtils.getScreenWidth(this) * 16 / 8

            val params = binding.myGLSurfaceView.layoutParams as FrameLayout.LayoutParams
            params.height = heightPic8_16
            params.gravity = Gravity.BOTTOM
            binding.myGLSurfaceView.layoutParams = params
            binding.myGLSurfaceView.presetRecordingSize(ViewUtils.getScreenWidth(this), heightPic8_16)
            binding.myGLSurfaceView.setPictureSize(ViewUtils.getScreenWidth(this), heightPic8_16, true)

            updateLineStyle(heightPic8_16,Gravity.BOTTOM)

        } else if (cameraSizeType == 1) {

           // binding.ivCameraSize.setImageResource(R.drawable.icon_size_3_4_active)
            val heightPic3_4 = ViewUtils.getScreenWidth(this) * 4 / 3

            val params = binding.myGLSurfaceView.layoutParams as FrameLayout.LayoutParams
            params.height = heightPic3_4
            params.gravity = Gravity.CENTER
            binding.myGLSurfaceView.layoutParams = params
            binding.myGLSurfaceView.presetRecordingSize(ViewUtils.getScreenWidth(this), heightPic3_4)
            binding.myGLSurfaceView.setPictureSize(ViewUtils.getScreenWidth(this), heightPic3_4, true)

            updateLineStyle(heightPic3_4,Gravity.CENTER)

        } else if (cameraSizeType == 2) {
          //  binding.ivCameraSize.setImageResource(R.drawable.icon_size_1_1_active)

            val heightPic1_1 = ViewUtils.getScreenWidth(this)

            val params = binding.myGLSurfaceView.layoutParams as FrameLayout.LayoutParams
            params.height = heightPic1_1
            params.gravity = Gravity.CENTER
            binding.myGLSurfaceView.layoutParams = params
            binding.myGLSurfaceView.presetRecordingSize(ViewUtils.getScreenWidth(this), heightPic1_1)
            binding.myGLSurfaceView.setPictureSize(ViewUtils.getScreenWidth(this), heightPic1_1, true)

            updateLineStyle(heightPic1_1,Gravity.CENTER)
        }

        binding.myGLSurfaceView.onResume()
        binding.myGLSurfaceView.setFilterWithConfig(currentFilterConfig)

    }

    private fun changeCountDown(time: Int) {
        cameraCountDown = time

        if (cameraCountDown == 0) {
            binding.ivTimeCountDown.setImageResource(R.drawable.ic_time_count_now_active)
        } else if (cameraCountDown == 3) {
            binding.ivTimeCountDown.setImageResource(R.drawable.ic_time_count_3_active)
        } else if (cameraCountDown == 5) {
            binding.ivTimeCountDown.setImageResource(R.drawable.ic_time_count_5_active)
        } else if (cameraCountDown == 10) {
            binding.ivTimeCountDown.setImageResource(R.drawable.ic_time_count_10_active)
        }

    }


    private fun animationTab(type:Int){
        if(type == cameraType){
            return
        }
        showSingleInterstitial(type)
        changeTakeStatus(type)

        val animator = binding.layoutCameraType.animate()
        animator.duration = 600
        animator.interpolator = AccelerateDecelerateInterpolator()
        when(type) {
            0 -> animator.translationX(68.dp.toFloat())
            1 -> animator.translationX(0f)
            2 -> animator.translationX(-68.dp.toFloat())
        }
        animator.setListener(object :AnimatorListener{
            override fun onAnimationStart(p0: Animator) {}

            override fun onAnimationEnd(p0: Animator) {
                val tabViews = arrayOf(binding.tvCameraVideo, binding.tvCameraImage, binding.tvCameraPuzzle)

                // 重置所有tab为普通状态
                tabViews.forEach { tabView ->
                    tabView.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
                    tabView.isSelected = false
                    tabView.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.title_color))
                }

                // 设置选中tab为高亮状态
                tabViews[type].apply {
                    typeface = Typeface.defaultFromStyle(Typeface.BOLD)
                    setTextColor(ContextCompat.getColor(context, R.color.color_green))
                    isSelected =  true
                }
            }

            override fun onAnimationCancel(p0: Animator) {}
            override fun onAnimationRepeat(p0: Animator) {}
        })
        animator.start()
        cameraType = type
    }


    private var maskType = 0
    private var maskId = 0
    private var currentMask: CustomMaskHandle?=null
    private val editMaskDialog:MaskEditDialog by lazy {
        val dialog = MaskEditDialog(this)
        dialog
    }
    private fun showMaskView(){

        binding.layoutMaskContainer.removeAllViews()
        val maskView = MaskConfig.getMaskView(this, maskType,maskId)
        currentMask = maskView
        binding.layoutMaskContainer.addView(maskView)

    }

    private fun changeTakeStatus(type:Int){
        if(type == 0){
            binding.ivTakePicture.visibility = View.GONE
            binding.ivTakeVideo.visibility = View.VISIBLE
            binding.tvTakePuzzle.visibility = View.GONE
            binding.tvChangePuzzle.visibility = View.INVISIBLE
            binding.layoutPuzzleContainer.visibility = View.INVISIBLE

        }else if(type == 1){
            binding.ivTakePicture.visibility = View.VISIBLE
            binding.ivTakeVideo.visibility = View.GONE
            binding.tvTakePuzzle.visibility = View.GONE
            binding.tvChangePuzzle.visibility = View.INVISIBLE
            binding.layoutPuzzleContainer.visibility = View.INVISIBLE

        }else if(type == 2){
            binding.ivTakePicture.visibility = View.GONE
            binding.ivTakeVideo.visibility = View.GONE
            binding.tvTakePuzzle.visibility = View.VISIBLE
            binding.tvChangePuzzle.visibility = View.VISIBLE
            binding.layoutPuzzleContainer.visibility = View.VISIBLE

            if(binding.layoutPuzzleContainer.childCount == 0){
                val puzzle = PuzzleStyle1(this)
                puzzleStyleViewUpdate = puzzle
                binding.layoutPuzzleContainer.addView(puzzle)

            }

        }
    }


    private fun recordingUIStatus(isRecording:Boolean){
        lifecycleScope.launch(Dispatchers.Main) {
            if(isRecording){
                binding.tvRecordingTime.visibility = View.VISIBLE
                binding.layoutTopHandle.visibility = View.INVISIBLE

                binding.layoutAlbum.visibility  = View.INVISIBLE
               // binding.tvCameraFilter.visibility  = View.INVISIBLE
                binding.tvLocation.visibility  = View.INVISIBLE
                binding.tvMask.visibility  = View.INVISIBLE

                binding.layoutCameraType.visibility  = View.INVISIBLE

                binding.ivTakeVideo.setImageResource(R.drawable.ic_index_camera_video_recording)
                ToastUtils.show("开始录制")
               // showDoubleChaPin()
            }else{
                binding.tvRecordingTime.visibility = View.INVISIBLE
                binding.layoutTopHandle.visibility = View.VISIBLE
                binding.layoutAlbum.visibility  = View.VISIBLE
               // binding.tvCameraFilter.visibility  = View.VISIBLE
                binding.tvLocation.visibility  = View.VISIBLE
                binding.tvMask.visibility  = View.VISIBLE

                binding.layoutCameraType.visibility  = View.VISIBLE

            }
        }

    }


    private fun changePuzzle(){

        if(puzzleList.isNotEmpty()){
            binding.tvTakePuzzle.text = "再拍\n一张"
            //水印
            binding.layoutFlash1.visibility = View.GONE
            //相册
            binding.layoutAlbum.visibility = View.GONE

            //撤销
            binding.rlPuzzleRepeal.visibility = View.VISIBLE
            //保存
            binding.rlPuzzleSave.visibility = View.VISIBLE
            //拍摄类型
            binding.layoutCameraType.visibility = View.INVISIBLE

            //选择模版
            binding.tvChangePuzzle.visibility = View.INVISIBLE

            //退出连拍
            //binding.tvQuitePuzzle.visibility = View.VISIBLE
            //连拍个数
            binding.tvPuzzleCount.visibility = View.VISIBLE
            binding.tvPuzzleCount.text = "已拍${puzzleList.size}张"
        } else{

            //水印
            binding.layoutFlash1.visibility = View.VISIBLE
            //相册
            binding.layoutAlbum.visibility = View.VISIBLE

            //撤销
            binding.rlPuzzleRepeal.visibility = View.GONE
            //保存
            binding.rlPuzzleSave.visibility = View.GONE
            //拍摄类型
            binding.layoutCameraType.visibility = View.VISIBLE

            //选择模版
            binding.tvChangePuzzle.visibility = View.VISIBLE

            //退出连拍
           // binding.tvQuitePuzzle.visibility = View.GONE

            //连拍个数
            binding.tvTakePuzzle.text = ""
            binding.tvPuzzleCount.visibility = View.GONE
        }
        puzzleStyleViewUpdate?.update(puzzleList.size)



        var ratioWidth = 9
        var ratioHeight = 16
        if(cameraSizeType == 1){
            ratioWidth = 3
            ratioHeight = 4
        }else if(cameraSizeType == 2){
            ratioWidth = 1
            ratioHeight = 1
        }
        if (puzzleStyle == 1 && puzzleList.size == 3){
            PuzzleActivity.launch(this,puzzleList,puzzleStyle,ratioWidth,ratioHeight)
        }else if(puzzleStyle == 2 && puzzleList.size == 4){
            PuzzleActivity.launch(this,puzzleList,puzzleStyle,ratioWidth,ratioHeight)
        }else if(puzzleStyle == 3 && puzzleList.size == 6){
            PuzzleActivity.launch(this,puzzleList,puzzleStyle,ratioWidth,ratioHeight)
        }else if(puzzleStyle == 4 && puzzleList.size == 9){
            PuzzleActivity.launch(this,puzzleList,puzzleStyle,ratioWidth,ratioHeight)
        }



    }

    private val puzzleStyleDialog:PuzzleStyleDialog by lazy {
       val dialog =  PuzzleStyleDialog(this)
        dialog.listener = object :PuzzleStyleDialog.OnPuzzleStyleChangeListener{
            override fun onChange(style: Int) {
                if (style != puzzleStyle){
                    puzzleStyle = style
                    changePuzzleStyle()
                }
            }
        }
        dialog
    }

    //更换拼图样式
    private fun changePuzzleStyle(){
        if (binding.layoutPuzzleContainer.childCount > 0){
            binding.layoutPuzzleContainer.removeAllViews()
        }

        if (puzzleStyle == 1){
            val puzzle = PuzzleStyle1(this)
            puzzleStyleViewUpdate = puzzle
            binding.layoutPuzzleContainer.addView(puzzle)
        }else if (puzzleStyle == 2){
            val puzzle = PuzzleStyle2(this)
            puzzleStyleViewUpdate = puzzle
            binding.layoutPuzzleContainer.addView(puzzle)
        }else if (puzzleStyle == 3){
            val puzzle = PuzzleStyle3(this)
            puzzleStyleViewUpdate = puzzle
            binding.layoutPuzzleContainer.addView(puzzle)
        }else if (puzzleStyle == 4){
            val puzzle = PuzzleStyle4(this)
            puzzleStyleViewUpdate = puzzle
            binding.layoutPuzzleContainer.addView(puzzle)
        }
    }


    /**
     * 展示单插屏
     */



    private fun showSingleInterstitial(position: Int) {
        AdManager.loadChapin(
            this,
            position,
            object : IAdViewListener {
                override fun onTrigger(adView: IAdView) {

                }

                override fun onAdShow(adView: IAdView) {

                }

                override fun onAdClick(adView: IAdView) {
                }

                override fun onAdClose(adView: IAdView) {
                    when (position) {
                        3 -> {
                            cameraPermissionRequest()
                        }
                    }
                }

                override fun onError(msg: String) {

                }

                override fun onLoadError(adView: IAdView) {

                }

                override fun onSuccess(adView: IAdView) {

                }

                override fun onLoad(adView: IAdView) {

                }

                override fun onSkipped() {

                }

                override fun onNoAd() {

                }

                override fun onTimeOut() {

                }
            },
            object : AdLoadListener {
                override fun onAdLoadFailed(ad: IAdView?) {
                }


            })
    }

    private fun cameraPermissionRequest(){
        var title = "权限申请"
        var content = ""
        if(!XXPermissions.isGranted(this,Permission.CAMERA) && !XXPermissions.isGranted(this,Permission.WRITE_EXTERNAL_STORAGE)){
            content = "本软件需要相机权限和存储权限才能正常拍摄存储图片或者视频,请开启授予相关权限"
        }else if(!XXPermissions.isGranted(this,Permission.CAMERA)){

            title = "相机权限申请"
            content = "本软件需要相机权限才能正常拍摄图片或者视频,请开启授予相关权限"
        }else if (!XXPermissions.isGranted(this,Permission.WRITE_EXTERNAL_STORAGE)){
            title = "存储权限申请"
            content = "本软件需要存储权限才能正常存储图片或者视频,请开启授予相关权限"
        }
        permissionTipTitle = title
        permissionTipContent = content
        permissionDialog.showDialog(title,content,Permission.CAMERA)
    }

    private fun videoPermissionRequest(){
        XXPermissions.with(this@MainActivity)
            .permission(Permission.CAMERA,Permission.WRITE_EXTERNAL_STORAGE,Permission.RECORD_AUDIO)
            .request(object:OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    defNotification?.hide()
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    super.onDenied(permissions, doNotAskAgain)
                    defNotification?.hide()
                    permissions.forEach {
                        if (it == Permission.CAMERA){
                            if (doNotAskAgain) {
                                val count = PermissionRequestPreference.instance.getCameraCount()
                                if (count == 0) {
                                    PermissionRequestPreference.instance.setCameraCount(count + 1)
                                    return
                                }
                                XXPermissions.startPermissionActivity(this@MainActivity, Permission.CAMERA)
                                return@forEach
                            }

                        }else if(it == Permission.WRITE_EXTERNAL_STORAGE){
                            if (doNotAskAgain) {
                                val count = PermissionRequestPreference.instance.getStorage()
                                if (count == 0) {
                                    PermissionRequestPreference.instance.setStorage(count + 1)
                                    return
                                }
                                XXPermissions.startPermissionActivity(this@MainActivity, Permission.WRITE_EXTERNAL_STORAGE)
                                return@forEach
                            }
                        }else if(it == Permission.RECORD_AUDIO){
                            if (doNotAskAgain) {
                                val count = PermissionRequestPreference.instance.getAudioCount()
                                if (count == 0) {
                                    PermissionRequestPreference.instance.setAudioCount(count + 1)
                                    return
                                }
                                XXPermissions.startPermissionActivity(this@MainActivity, Permission.RECORD_AUDIO)
                                return@forEach
                            }
                        }

                    }
                }
            })
    }

    private fun albumPermissionRequest(){
        XXPermissions.with(this@MainActivity)
            .permission(Permission.WRITE_EXTERNAL_STORAGE)
            .request(object:OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    defNotification?.hide()
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    super.onDenied(permissions, doNotAskAgain)
                    defNotification?.hide()
                    if (doNotAskAgain) {
                        val count = PermissionRequestPreference.instance.getStorage()
                        if (count == 0) {
                            PermissionRequestPreference.instance.setStorage(count + 1)
                            return
                        }
                        XXPermissions.startPermissionActivity(this@MainActivity, Permission.WRITE_EXTERNAL_STORAGE)
                    }
                }
            })
    }

    private fun requestAlbumPermission(){
        XXPermissions.with(this@MainActivity)
            .permission(Permission.READ_MEDIA_IMAGES)
            .request(object :OnPermissionCallback{
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    defNotification?.hide()
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    super.onDenied(permissions, doNotAskAgain)
                    defNotification?.hide()
                    if (doNotAskAgain) {
                        val count = PermissionRequestPreference.instance.getAlbumRequestCount()
                        if (count == 0) {
                            PermissionRequestPreference.instance.setAlbumRequestCount(count + 1)
                            return
                        }
                        XXPermissions.startPermissionActivity(this@MainActivity, Permission.READ_MEDIA_IMAGES)
                    }
                }
            })

    }

    private fun drawEvents(){

        binding.layoutVip.clickWithTrigger {

            VipCenterActivity.launch(this)
        }

        binding.layoutUserInfo.clickWithTrigger {
//               if (logininfo?.token.isNullOrEmpty()){
//                    binding.layoutDrawer.close()
//                   LoginActivity.launch(this)
//               }else{
//                   binding.layoutDrawer.close()
//                   AccountSettingActivity.launch(this)
//               }

        }



//        binding.ivCloseDrawer.clickWithTrigger {
//            binding.layoutDrawer.close()
//        }
        binding.sbLogoWaterMark.setOnCheckedChangeListener { compoundButton, b ->
//            if (!b){
//                if (userInfo == null || !UserPreference.instance.isVip()){
//                    //非VIP
//                    VipCenterActivity.launch(this)
//                    isNeedLogoWaterMark = true
//                    SettingPreference.instance.setLogoWaterMark(true)
//                    binding.sbLogoWaterMark.isChecked = true
//                    return@setOnCheckedChangeListener
//                }
//            }
            isNeedLogoWaterMark = b
            SettingPreference.instance.setLogoWaterMark(b)
        }

        binding.layoutCameraSetting.clickWithTrigger {
            binding.layoutDrawer.close()
            CameraSettingActivity.launch(this)
        }


//        binding.layoutUserInfo.clickWithTrigger {
//            LoginActivity.launch(this)
//        }
//
//        binding.btnLogin.clickWithTrigger {
//            LoginActivity.launch(this)
//        }


        binding.layoutUserProtocol.clickWithTrigger {
            WebViewActivity.launch(this,"用户服务协议", Constants.PrivacyUrl.protocol.url)
        }
        binding.layoutPrivacy.clickWithTrigger {
            WebViewActivity.launch(this,"隐私政策",Constants.PrivacyUrl.privacy.url)
        }

        binding.layoutFeedBack.clickWithTrigger {
            binding.layoutDrawer.close()
            FeedBackActivity.launch(this)
        }
        binding.layoutAboutUs.clickWithTrigger {
            binding.layoutDrawer.close()
            AboutActivity.launch(this)
        }

        binding.layoutContactUs.clickWithTrigger {
            binding.layoutDrawer.close()
            qqDialog.show()
        }

        initZoomButtons()
    }


    // 在 MainActivity 类中添加以下代码

    private var selectedButtonIndex = 1 // 0: 第一个按钮, 1: 第二个按钮, 2: 第三个按钮

    private fun initZoomButtons() {
        // 为三个按钮设置点击事件
        binding.btnZoom05.clickWithTrigger {
            handleButtonClick(0)
        }

        binding.btnZoom1.clickWithTrigger {
            handleButtonClick(1)
        }

        binding.btnZoom2.clickWithTrigger {
            handleButtonClick(2)
        }
    }

    private fun handleButtonClick(buttonIndex: Int) {
        if (!XXPermissions.isGranted(this@MainActivity,Permission.CAMERA)){
            ToastUtils.show("请先打开相机权限")
            return
        }
        if (selectedButtonIndex != buttonIndex) {
            selectedButtonIndex = buttonIndex
            updateButtonStyle(buttonIndex)
        }
    }

    private fun updateButtonStyle(selectedIndex: Int) {
        val buttons = arrayOf(binding.btnZoom05, binding.btnZoom1, binding.btnZoom2)
        buttons.forEachIndexed { index, button: ShapeTextView ->
            if (index == selectedIndex) {
                button.shapeDrawableBuilder
                    .setSolidColor(ContextCompat.getColor(this, R.color.alpha_black))
                    .intoBackground()
            } else {
                button.shapeDrawableBuilder
                    .setSolidColor(ContextCompat.getColor(this, R.color.aplapha))
                    .intoBackground()
            }
        }
        when(selectedIndex){
            0 -> {
                zoom = 0
            }
            1 -> {
                zoom = 2
            }
            2 -> {
                zoom = 4
            }
        }
        var params = binding.myGLSurfaceView.cameraInstance().params
        params.zoom = zoom
        binding.myGLSurfaceView.cameraInstance().params = params
    }


    private val vibrator:Vibrator by lazy {
       getSystemService(VIBRATOR_SERVICE) as Vibrator
   }
    private fun takeVibrator(){
        if (vibrator.hasVibrator() && takeVibrating){
            vibrator.vibrate(200)
        }

    }
    private val audio:AudioManager by lazy{
        getSystemService(Service.AUDIO_SERVICE) as AudioManager
    }
    private fun playTakeSound(){

        if (takeSound){
            mMediaPlayer.start()
        }else{
            currentPhoneVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC)
            audio.setStreamVolume(AudioManager.STREAM_MUSIC,0,AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE)
        }
    }
    private val qqDialog:ContactUsDialog by lazy {
        ContactUsDialog(this)
    }

    //拍照抽取代码
    private fun takePhotoWithMask(photo:Bitmap,mask:Bitmap){
        val finalBitmap =  ImageUtil.createWaterMaskLeftBottom(photo,mask,-5,15)
        //存储到私有目录---无水印照片--名字要是一样带
        val name = "today_mask_${System.currentTimeMillis()}.png"
        lifecycleScope.launch(Dispatchers.IO) {
            //无水印存储到私有目录
            CommonUtils.saveBitmapToCache(photo,getExternalFilesDir(Constants.NO_MASK_CACHE_IMAGE)!!,name)
        }

        if(isNeedSaveAlbum){

            lifecycleScope.launch(Dispatchers.IO) {
                //水印图存储到相册
                val uri = finalBitmap?.saveToAlbum(this@MainActivity,name,null,100)
                lifecycleScope.launch(Dispatchers.Main) {
                    binding.ivAlbum.load(uri)
                    currentCameraUri = uri
                    loadingPop.dismissLoading()
                }
            }

        }else{
            lifecycleScope.launch(Dispatchers.IO) {
                //无水印存储到私有目录
                val cachePath =  CommonUtils.saveBitmapToCache(finalBitmap,getExternalFilesDir(Constants.HAVE_MASK_CACHE_IMAGE)!!,name)

                lifecycleScope.launch(Dispatchers.Main) {
                    loadingPop.dismissLoading()
                    EditImageActivity.launchShare(this@MainActivity,cachePath)
                }
            }
        }

    }



    private fun updateLineStyle(heightWindow:Int,gravity:Int){
        val lineParent = binding.includeLine.root.layoutParams as FrameLayout.LayoutParams
        lineParent.height = heightWindow
        lineParent.gravity = gravity
        binding.includeLine.root.layoutParams = lineParent

        val hLine1Params = binding.includeLine.viewH1.layoutParams as FrameLayout.LayoutParams
        hLine1Params.topMargin = heightWindow/3
        binding.includeLine.viewH1.layoutParams = hLine1Params

        val hLine2Params = binding.includeLine.viewH2.layoutParams as FrameLayout.LayoutParams
        hLine2Params.topMargin =  heightWindow*2/3
        binding.includeLine.viewH2.layoutParams = hLine2Params


        val vLine1Params = binding.includeLine.viewV1.layoutParams as FrameLayout.LayoutParams
        vLine1Params.leftMargin = ViewUtils.getScreenWidth(this)/3
        binding.includeLine.viewV1.layoutParams = vLine1Params

        val vLine2Params = binding.includeLine.viewV2.layoutParams as FrameLayout.LayoutParams
        vLine2Params.leftMargin = ViewUtils.getScreenWidth(this)*2/3
        binding.includeLine.viewV2.layoutParams = vLine2Params

    }

    private fun initUser(){

     //    logininfo=MMKVUtils.getObject(com.hlyj.http.base.tool.lib_hlyj_base.Constants.LoginResultBean,LoginResultBean::class.java)
 //       if (logininfo!=null){
//            logininfo?.token?.let { getUserInfo(it) }//获取用户信息接口
//            if (logininfo?.phone.isNullOrEmpty()){
//                binding.tvUserName.text = "水印相机用户"
//            }else{
//                binding.tvUserName.text = phoneHide(logininfo?.phone?:"")
//            }


////            if (userInfo?.vipType != 0){
//            if (UserPreference.instance.isVip()){
//                //vip
//                binding.ivVipTxt.visibility = View.VISIBLE
//                binding.tvVipStatus.text = Constants.getVipTxt(userInfo?.vipType?:0)
//                binding.tvVipExpirationTime.visibility = View.VISIBLE
//                if (userInfo?.vipType == 0){
//                    //临时vip
//                    binding.tvVipExpirationTime.text = "有效期至:即将到期"
//                }else if (userInfo?.vipType == 1){
//                    binding.tvVipExpirationTime.text = "有效期至:永久VIP"
//                }else{
//                    binding.tvVipExpirationTime.text = "有效期至:${TimeUtil.changeIsoTime(userInfo?.vipTime?:"")}"
//                }
//
//               // binding.ivLogoMask.visibility = View.INVISIBLE
//            }else{
//                //非vip
//                binding.ivVipTxt.visibility = View.GONE
//                binding.tvVipStatus.text = "相机会员"
//                binding.tvVipExpirationTime.visibility = View.VISIBLE
//                binding.tvVipExpirationTime.text = "AI去水印/无限拍摄/高级功能"
//               // binding.ivLogoMask.visibility = View.VISIBLE
//            }


//        }else{
//           // logininfo = null
//            binding.tvUserName.text = "水印相机用户"
//            binding.ivUserPhoto.setImageResource(R.drawable.ic_default_header)
//
//            binding.ivVipTxt.visibility = View.GONE
//            binding.tvVipStatus.text = "相机会员"
//            binding.tvVipExpirationTime.visibility = View.VISIBLE
//            binding.tvVipExpirationTime.text = "解锁APP全部功能使用权限"
//            //binding.ivLogoMask.visibility = View.VISIBLE
//
//        }


    }

   private fun startTempVipTimeTask(){

       val tempVipStartTime = UserPreference.instance.getTempExpirationTime()
       if (tempVipStartTime == 0L){
           UserPreference.instance.setTempVip(false)
           return
       }
       val currentTime = SystemClock.elapsedRealtime()
       if ((currentTime - tempVipStartTime) > Constants.tempVipTime- 5*1000){
           UserPreference.instance.setTempVip(false)
           return
       }

       var count = ((Constants.tempVipTime) - (currentTime - tempVipStartTime)).toInt()
       count /= 1000

       CommonUtils.countDownCoroutines(count,{
           XLog.e("=====vip倒计时${it}")
       },{//停止也到期了 需要判断时间
           val currentTime = SystemClock.elapsedRealtime()
           if ((currentTime - tempVipStartTime) > Constants.tempVipTime - 10*1000){
               XLog.e("=====vip到期了")
               UserPreference.instance.setTempVip(false)
               //发送事件刷新
               sendEvent(TempVipExpireEvents(true))
           }

       },lifecycleScope)
   }
    private fun permissionNotification(titleTxt:String,contentTxt:String){
        val title: TextView? = defNotification?.findViewById(R.id.title)
        title?.text = titleTxt
        val content: TextView? = defNotification?.findViewById(R.id.content)
        content?.text = contentTxt

        defNotification?.show()
    }


    private var exitTime = 0L
    override fun onBackPressed() {
        if(System.currentTimeMillis() - exitTime > 2000) {
            ToastUtils.show("再按一次退出")
            exitTime = System.currentTimeMillis()
        } else {
            super.onBackPressed()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(timeChangeReceiver)
        mLocationClient.stopLocation()
        mLocationClient.onDestroy()
        recordIngJob?.cancel()


    }
   //新增广告流程
   fun app_process_1() {
       type_proces = "第一次进首页插屏"
       AdManager.loadTwoChapinSimultaneously(
           this,
           2,
           this,
           object : AdLoadListener {
               override fun onAdLoadFailed(ad: IAdView?) {
                   Log.e("qin", "首页流程1插屏加载失败")
                   if (!SpUtils.getInstance().getBooleanWithTimeoutCheck(BaseAppConstans.IS_SHOW_FUNCTION_DIALOG)){
                           showFunctionGuideDialog(this@MainActivity)
                   }
               }
           })
   }
    fun app_process_2() {
        type_proces = "第一次进首页插屏"
        AdManager.loadTwoChapinSimultaneously(
            this,
            2,
            this,
            object : AdLoadListener {
                override fun onAdLoadFailed(ad: IAdView?) {
                    Log.i("qin", "首页流程2插屏加载失败")
                    if (!SpUtils.getInstance().getBooleanWithTimeoutCheck(BaseAppConstans.IS_SHOW_FUNCTION_DIALOG)){
                        showFunctionGuideDialog(this@MainActivity)
                    }

                }
            })
    }
    /**
     * 显示功能引导弹窗
     */
    private fun showFunctionGuideDialog(context: Context) {
        // 创建对话框实例
        val dialog = FunctionGuideDialog(context)
        dialog.setCancelable(false) // 设置对话框不可取消
        dialog.setOnGuideDialogListener(object : FunctionGuideDialog.onGuideDialogListener {
            override fun btnOnclick() {
                dialog.dismiss() // 关闭对话框
                // 处理点击引导内容的回调
                type_proces = "功能弹窗"
                AdManager.loadVideo(
                    this@MainActivity,
                    4,
                    this@MainActivity,
                    object : AdLoadListener {
                        override fun onAdLoadFailed(ad: IAdView?) {
//                            val intent = Intent(requireActivity(), YuErButieActivity::class.java)
//                            activityLauncher.launch(intent)
                        }
                    })

            }

            override fun btnOnclose() {
                // 处理关闭按钮的回调
                dialog.dismiss() // 关闭对话框
            }
        })

// 显示对话框
        dialog.show()

    }
    /**
     * 显示隐私协议弹窗
     */
    private fun showAgreementtDialog() {
        if (SpUtils.getInstance().getBoolean(BaseAppConstans.isAgreeMent)) {

            return
        }
        var dialog = UserAgreementDialog(this)
        dialog!!.show()
        dialog!!.setPrivateId("您好"+"("+ BaseModuleSpUtils.getInstance().getString(com.hlyj.http.base.tool.lib_hlyj_base.Constants.PRIVACYID)+")")
        dialog!!.setCancelable(false)
        dialog!!.setOnAgreementListener(object : UserAgreementDialog.AgreementDialogListner {
            override fun onDialogListener(clickType: Boolean) {
                if (clickType) {
                    SpUtils.getInstance().putBoolean(BaseAppConstans.isAgreeMent, true)
                    if (!SpUtils.getInstance().getBoolean(BaseAppConstans.IS_SHOW_YINSI_CHAPIN)){
                        type_proces="特殊情况点击同意隐私的插屏"
                        AdManager.loadTwoChapinSimultaneously(
                            this@MainActivity,
                            10,
                            this@MainActivity,
                            object : AdLoadListener {
                                override fun onAdLoadFailed(ad: IAdView?) {

                                }
                            })
                    }

                } else { //拒绝隐私协议
                    finish()

                }
            }
        })
    }
    override fun onTrigger(adView: IAdView) {

    }

    override fun onAdShow(adView: IAdView) {

    }

    override fun onAdClick(adView: IAdView) {

    }

    override fun onAdClose(adView: IAdView) {
        when(type_proces){
                "第一次进首页插屏"->{
                // Log.e("qin","第一次进首页插屏执行了吗")
                if (!SpUtils.getInstance().getBooleanWithTimeoutCheck(BaseAppConstans.IS_SHOW_FUNCTION_DIALOG)){
                    showFunctionGuideDialog(this)
                }else{
                    if (!SpUtils.getInstance().getBoolean(BaseAppConstans.isAgreeMent)) {
                        showAgreementtDialog()
                    }

                }
            }
            "功能弹窗关闭广告" -> {
                if (app_process == "1") {
                    showAgreementtDialog()
                }

            }
            "功能弹窗" -> {
                if (app_process == "1") {
                    type_proces = "功能弹窗关闭广告"
                    AdManager.loadTwoChapinSimultaneously(
                        this@MainActivity,
                        5,
                        this@MainActivity,
                        object : AdLoadListener {
                            override fun onAdLoadFailed(ad: IAdView?) {
                                if (app_process == "1") {
                                    showAgreementtDialog()
                                }
                            }
                        })
                }
            }
        }
    }

    override fun onError(msg: String) {

    }

    override fun onLoadError(adView: IAdView) {

    }

    override fun onSuccess(adView: IAdView) {

    }

    override fun onLoad(adView: IAdView) {

    }

    override fun onSkipped() {

    }

    override fun onNoAd() {

    }

    override fun onTimeOut() {

    }

    private fun phoneHide(phone: String): String {
        val sb = StringBuilder()
        if (!TextUtils.isEmpty(phone) && phone.length > 6) {
            for (i in phone.indices) {
                val c = phone[i]
                if (i in 3..6) {
                    sb.append('*')
                } else {
                    sb.append(c)
                }
            }
        }
        return sb.toString()
    }

    /**
     * 获取用户信息
     */
    private fun getUserInfo(token: String){
        GlobalApi.getUserInfo(token,object : ApiCallback<BaseResult<UserInfoResultBean?>?> {
            override fun onSuccess(result: BaseResult<UserInfoResultBean?>?) {

                MMKVUtils.saveObject(com.hlyj.http.base.tool.lib_hlyj_base.Constants.UserInfoResultBean, result?.data)
                result?.data?.isVip?.let {
                    BaseAdSpUtils.getInstance().putInt(BaseAdConstants.ISVIP,
                        it
                    )
                }

            }

            override fun onFailure(errorMessage: String) {
                ToastUtils.show(errorMessage)
            }

            override fun onFinish() {

            }

        })
    }

    //统一双插屏无需加位置
    fun showDoubleChaPin(){
        AdManager.loadTwoChapinSimultaneously(
            this,
            666,
            this,
            object : AdLoadListener {
                override fun onAdLoadFailed(ad: IAdView?) {

                }
            })
    }
}

